package com.jason.fingerprint.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.jason.fingerprint.AppContext;
import com.jason.fingerprint.R;
import com.jason.fingerprint.beans.AddLoginInfoReq;
import com.jason.fingerprint.beans.LoginReq;
import com.jason.fingerprint.beans.UserBean;
import com.jason.fingerprint.common.DialogHelper;
import com.jason.fingerprint.common.PreferenceHelper;
import com.jason.fingerprint.common.UIHelper;
import com.jason.fingerprint.configs.HttpConfig;
import com.jason.fingerprint.logic.DatbAddLoginSyncLogic;
import com.jason.fingerprint.logic.LoginSyncLogic;
import com.jason.fingerprint.ui.HomeActivity;
import com.jason.fingerprint.ui.LoginActivity;
import com.jason.fingerprint.widget.LoadingDialog;

import org.kymjs.aframe.ui.KJActivityManager;
import org.kymjs.aframe.utils.StringUtils;
import org.kymjs.aframe.utils.SystemTool;

import java.util.List;

@SuppressLint("HandlerLeak")
public class AccountLoginFragment extends Fragment implements OnClickListener,
		TextWatcher {

	private static final String TAG = "AccountLoginFragment";

	private Context mContext;
	private AppContext mAppContext;

	private EditText mAccountNameEditText;
	private EditText mAccountPwdEditText;
	private Button mAccountLoginButton;

	private RelativeLayout mLogoMainLayout;

	private String mAccountName;
	private String mAccountPwd;

	private LoadingDialog mProgressDialog;

	private boolean mIsFirst = true;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
							 Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_account_login,
				container, false);
		InitData();
		initView(view);
		updateWindowSoftState();
		return view;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.support.v4.app.Fragment#onResume()
	 */
	@Override
	public void onResume() {
		super.onResume();
	}

	private void initView(View view) {
		mAccountNameEditText = (EditText) view.findViewById(R.id.account_name);
		mAccountPwdEditText = (EditText) view.findViewById(R.id.account_pwd);
		mAccountLoginButton = (Button) view
				.findViewById(R.id.account_login_btn);

		if (!mAccountNameEditText.getText().toString().isEmpty()
				&& !mAccountPwdEditText.getText().toString().isEmpty()) {
			mAccountLoginButton.setEnabled(true);
		} else {
			mAccountLoginButton.setEnabled(false);
		}

		mAccountNameEditText.addTextChangedListener(this);
		mAccountPwdEditText.addTextChangedListener(this);

		mAccountLoginButton.setOnClickListener(this);
		mProgressDialog = new LoadingDialog(getActivity());

		mLogoMainLayout = (RelativeLayout) view.findViewById(R.id.account_logo_main);
	}

	private void InitData() {
		mContext = getActivity();
		mAppContext = (AppContext) getActivity().getApplication();
	}

	private void updateWindowSoftState(){
		final View decorView = getActivity().getWindow().getDecorView();
		decorView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
			@Override
			public void onGlobalLayout() {
				Rect rect = new Rect();
				decorView.getWindowVisibleDisplayFrame(rect);
				int displayHight = rect.bottom - rect.top;
				int hight = decorView.getHeight();
				boolean visible = (double) displayHight / hight < 0.8;

				if (visible) {
					System.out.println("软键盘打开了");
					mLogoMainLayout.setVisibility(View.GONE);
				} else {
					System.out.println("软键盘关闭了");
					mLogoMainLayout.setVisibility(View.VISIBLE);
				}
			}
		});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.account_login_btn:
				updateEditViewInfo();
				// TODO 请在线程中调用数据库操作，以免阻塞UI主线程
				if (SystemTool.checkNet(mContext)) {
					login();
				} else {
					// 弹出开启网络的弹出框，提示用户设置网络
					DialogHelper.openNetSettingsDialog(getActivity());
				}
				break;

			default:
				break;
		}
	}

	// 调用登录接口
	private void login() {
		updateEditViewInfo();
		if (StringUtils.isEmpty(mAccountName)
				|| StringUtils.isEmpty(mAccountPwd)) {
			Toast.makeText(mContext, "账号或密码为空，请重新输入", Toast.LENGTH_SHORT)
					.show();
			return;
		}
		// TODO Auto-generated method stub
		mProgressDialog.setIsOut(false);
		mProgressDialog.setMessage("请稍等，正在登陆中...");
		mProgressDialog.show();
		LoginReq req = new LoginReq(mAccountName, mAccountPwd, 1,
				LoginSyncLogic.LOGIN_ACCOUNT, HttpConfig.POST_URL_DATB_LOGIN);

		LoginSyncLogic logic = new LoginSyncLogic(mAppContext, mContext,
				mLoginHandler, true, req);
		logic.execute();

	}

	// 获取最新输入框的账号和密码信息
	private void updateEditViewInfo() {
		mAccountName = mAccountNameEditText.getText().toString();
		mAccountPwd = mAccountPwdEditText.getText().toString();
	}

	private Handler mLoginHandler = new Handler() {

		@Override
		public void handleMessage(android.os.Message msg) {
			if (mProgressDialog != null) {
				mProgressDialog.dismiss();
			}
			switch (msg.what) {
				case UIHelper.LOGIN_SUCCESS:
					if (!mIsFirst){
						return;
					}
					mIsFirst = false;
					Toast.makeText(mContext, "登录成功", Toast.LENGTH_SHORT).show();
					List<UserBean> userBeans = (List<UserBean>)msg.obj;
					UserBean bean = getAccountUserBean(userBeans);
					Log.i(TAG, "----->mLoginHandler " + bean);
					if (bean != null) {
						int userId = PreferenceHelper.getUserId(mContext);
						if (userId != bean.getUserId()){
							PreferenceHelper.setUpdateStatus(mContext,true);
						}else{
							PreferenceHelper.setUpdateStatus(mContext,false);
						}
						PreferenceHelper.saveLoginInfoToPreference(mContext,
								bean);
						AppContext.getInstance().setUserBean(bean);
						PreferenceHelper.setUserId(mContext,bean.getUserId());
						AddLoginInfoReq req = new AddLoginInfoReq();
						req.setType(1);
						req.setLoginName(bean.getLoginName());
						req.setUserName(bean.getUserName());
						req.setOrganId(String.valueOf(bean.getOrganId()));
						req.setOrgan(bean.getOrgan());
						DatbAddLoginSyncLogic logic = new DatbAddLoginSyncLogic(
								mAppContext, new Handler(), false, req);
						logic.execute();
					}
					if (HomeActivity.mHomeActivity == null){
						Intent intent = new Intent(mContext, HomeActivity.class);
						intent.putExtra("is_to_loading_activity",true);
						startActivity(intent);
						LoginActivity.loginActivity.finish();
						LoginActivity.loginActivity = null;
					}
					break;
				case UIHelper.LOGIN_FAIL:
				case UIHelper.HTTP_CODE_TIMEOUT:
					Toast.makeText(mContext, msg.obj.toString(), Toast.LENGTH_SHORT).show();
					break;

				default:
					break;
			}

		};
	};

	private UserBean getAccountUserBean(List<UserBean> userBeans) {
		updateEditViewInfo();
		if (userBeans != null && !userBeans.isEmpty()) {
			String name = mAccountName;
			String pwd = mAccountPwd;
			int count = userBeans.size();
			for (int i = 0; i < count; i++) {
				UserBean bean = userBeans.get(i);
				if (!StringUtils.isEmpty(bean.getLoginName())
						&& !StringUtils.isEmpty(bean.getLoginPwd())
						&& !StringUtils.isEmpty(name)
						&& !StringUtils.isEmpty(pwd)) {
					if (bean.getLoginName().equals(name)
							&& bean.getLoginPwd().equals(pwd)) {
						return bean;
					}
				}
			}
		}
		return null;
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
								  int after) {

	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		if (!mAccountNameEditText.getText().toString().isEmpty()
				&& !mAccountPwdEditText.getText().toString().isEmpty()) {
			mAccountLoginButton.setEnabled(true);
		} else {
			mAccountLoginButton.setEnabled(false);
		}
	}

	@Override
	public void afterTextChanged(Editable s) {

	}


	@Override
	public void onDestroy() {
		super.onDestroy();
		if (mProgressDialog != null) {
			mProgressDialog.dismiss();
		}
	}
}
